<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <yanlei :msg-for-chen-ming-wang="msgForChenMingWang"></yanlei>
      <chenmingwang :msg-for-yan-lei="msgForYanLei"></chenmingwang>
    </div>

    <template id="yanlei">
      <div>
        <h1>我是闫磊</h1>
        <div>
          <input type="text" v-model="msg" />
          <button @click="sendMsg">发消息给陈名旺</button>
        </div>
        <div>收到了陈名旺的消息：{{ msgForChenMingWang }}</div>
      </div>
    </template>

    <template id="chenmingwang">
      <div>
        <h1>我是陈名旺</h1>
        <div>
          <input type="text" v-model="msg" />
          <button @click="sendMsg">发消息给闫磊</button>
        </div>
        <div>收到了闫磊的消息：{{ msgForYanLei }}</div>
      </div>
    </template>

    <script src="../vue.js"></script>
    <script>
      // 所谓的事件中心就是一个空的Vue实例，仅仅用来充当事件传递者
      const eventHub = new Vue();
      // eventHub.$on 监听自定义事件
      // eventHub.$emit 触发自定义事件

      new Vue({
        el: '#app',
        components: {
          yanlei: {
            template: '#yanlei',
            data() {
              return {
                msg: 'hehe',
                msgForChenMingWang: '',
              };
            },
            methods: {
              sendMsg() {
                eventHub.$emit('msg-of-yan-lei', this.msg);
              },
            },
            created() {
              eventHub.$on('msg-of-chen-ming-wang', (msg) => {
                this.msgForChenMingWang = msg;
              });
            },
          },
          chenmingwang: {
            template: '#chenmingwang',
            data() {
              return {
                msg: 'haha',
                msgForYanLei: '',
              };
            },
            methods: {
              sendMsg() {
                eventHub.$emit('msg-of-chen-ming-wang', this.msg);
              },
            },
            created() {
              eventHub.$on('msg-of-yan-lei', (msg) => {
                this.msgForYanLei = msg;
              });
            },
          },
        },
        data: {
          msgForYanLei: '',
          msgForChenMingWang: '',
        },
        methods: {
          onSendMsgForChenMingWang(msg) {
            this.msgForChenMingWang = msg;
          },
          onSendMsgForYanLei(msg) {
            console.log('APP组件', msg);
            this.msgForYanLei = msg;
          },
        },
      });
    </script>
  </body>
</html>
